package com.googlecode.sparda.commons.concurrent;

import java.util.concurrent.ThreadFactory;

/**
 * A simple {@link ThreadFactory} to manage thread name.
 * @author Fabio Grucci (<i>alias</i> <b>Phoenix</b>)
 * @since 1.0
 * @version 1.0
 */
public class SimpleThreadFactory implements ThreadFactory {
	/**
	 * The {@link ThreadGroup}.
	 */
	private final ThreadGroup threadGroup;
	/**
	 * The base {@link Thread} name.
	 */
	private final String newThreadBaseName;
	/**
	 * The number of {@link Thread} created by this factory.
	 */
	private int threadCount;
	
	/**
	 * Build a {@link SimpleThreadFactory} whit a name for the thread group.
	 * It is equivalent to {@link #SimpleThreadFactory(String, String)} with
	 * arguments threadGroupName threadGroupName.
	 * @param threadGroupName The name of the thread group.
	 */
	public SimpleThreadFactory(String threadGroupName) {
		this(threadGroupName, threadGroupName);
	}
	/**
	 * Build a {@link SimpleThreadFactory} with a threadGroupName a a threadBaseName.
	 * The factory will create a {@link ThreadGroup} with threadGroupName, 
	 * and {@link Thread} with threadBaseName + " #" + threadNumber. 
	 * @param threadGroupName The name of {@link ThreadGroup}
	 * @param newThreadBaseName The base name of {@link Thread}
	 */
	public SimpleThreadFactory(String threadGroupName, String newThreadBaseName) {
		this.threadGroup = new ThreadGroup(threadGroupName);
		this.newThreadBaseName = newThreadBaseName + " #";
	}
	
	/*
	 * (non-Javadoc)
	 * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
	 */
	@Override
	public Thread newThread(Runnable r) {
		return new Thread(this.threadGroup, r, this.newThreadBaseName + ++this.threadCount);
	}

}